package com.hmall.common.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeansException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
@ConditionalOnClass(RabbitTemplate.class)
public class RabbitTemplateConfig implements ApplicationContextAware {
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        RabbitTemplate rabbitTemplate = applicationContext.getBean(RabbitTemplate.class);
        //给RabbitTemplate绑定Return回调
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            /*
             * 如果消息成功路由到队列，这个方法不会被调用
             * 如果消息未到达队列，这个方法会被调用：消息会被退回来
             */
            @Override
            public void returnedMessage(ReturnedMessage returnedMessage) {
                if(returnedMessage.getExchange().startsWith("delay")){
                    return;
                }
                log.error("消息未到达队列，exchange={},RoutingKey={},msg={},replyCode={},replyText={}",
                        returnedMessage.getExchange(),
                        returnedMessage.getRoutingKey(),
                        returnedMessage.getMessage(),
                        returnedMessage.getReplyCode(),
                        returnedMessage.getReplyText());
            }
        });
    }
}